package cn.edu.cqvie.netty.nio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class NioTest13 {


    public static void main(String[] args) throws IOException {
        String inputFile = "NioTest13_In.txt";
        String outputFile = "NioTest13_Out.txt";

        RandomAccessFile inputRandomAccessFile = new RandomAccessFile(inputFile, "r");
        RandomAccessFile outputRandomAccessFile = new RandomAccessFile(outputFile, "rw");

        long inputLength = new File(inputFile).length();

        FileChannel inputFileChannel = inputRandomAccessFile.getChannel();
        FileChannel outputFileChannel = outputRandomAccessFile.getChannel();

        //内存映射文件
        MappedByteBuffer inputData = inputFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, inputLength);

        System.out.println("=================");

        Charset.availableCharsets().forEach((k, v) -> {
            System.out.println(k + "," + v);
        });

        System.out.println("=================");

        //中文编码解码，ISO-8859-1 中间知识过度没有，丢失，目标文件依然是UTF8文件格式
        Charset charset = Charset.forName("iso-8859-1");
        //字节数组 => 字符串
        CharsetDecoder decoder = charset.newDecoder();
        //字符串 => 字节数组
        CharsetEncoder encoder = charset.newEncoder();

        CharBuffer charBuffer = decoder.decode(inputData);

        System.out.println(charBuffer.get(12));
        ByteBuffer outputData = encoder.encode(charBuffer);
        //会存在乱码如下：
        //ByteBuffer outputData = Charset.forName("utf-8").encode(charBuffer);
        outputFileChannel.write(outputData);

        inputFileChannel.close();
        outputFileChannel.close();

    }
}
